import { createFileRoute } from '@tanstack/react-router'
import { useState, useCallback, useEffect, useMemo } from 'react'
import { useAuth } from '@/providers/auth-provider'
import { LoginModal } from '@/components/login-modal'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { Badge } from '@/components/ui/badge'
import { Textarea } from '@/components/ui/textarea'
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'
import { Plus, TrendingUp, TrendingDown, DollarSign, PieChart, BarChart3, Edit, Search, Eye, EyeOff, Lock, Share2 } from 'lucide-react'
import { cn } from '@/lib/utils'
import { assetService } from '@/services/assetService'
import type { PortfolioOverview } from '@/types/assets'
import type { RevenueTrendData, ExpenseTrendData } from '@/types/trend'

export const Route = createFileRoute('/assets')({
    component: AssetsPage,
})

// 类型定义
interface AssetCategory {
  id: number
  name: string
  icon: string
  color: string
  total_value: number
  count: number
  balance?: number
  notes?: string
  status?: 'active' | 'inactive'
}

interface Asset {
  id: number
  name: string
  symbol: string
  category_id: number
  category_name: string
  quantity: number
  purchase_price: number
  current_price: number
  purchase_date: string
  total_value: number
  profit_loss: number
  profit_loss_percentage: number
  notes?: string
  balance?: number
  status?: 'active' | 'inactive'
}

interface AssetTransaction {
  id: number
  asset_id: number
  asset_name: string
  asset_symbol: string
  transaction_type: 'buy' | 'sell' | 'dividend' | 'transfer'
  quantity: number
  price: number
  total_amount: number
  transaction_date: string
  notes?: string
  balance_after?: number
}

// Mock 数据
const mockCategories: AssetCategory[] = [
  { id: 1, name: '股票', icon: 'TrendingUp', color: 'bg-blue-500', total_value: 150000, count: 5 },
  { id: 2, name: '基金', icon: 'PieChart', color: 'bg-green-500', total_value: 80000, count: 3 },
  { id: 3, name: '加密货币', icon: 'DollarSign', color: 'bg-orange-500', total_value: 25000, count: 4 },
  { id: 4, name: '债券', icon: 'BarChart3', color: 'bg-purple-500', total_value: 60000, count: 2 },
  { id: 5, name: '房产', icon: 'TrendingUp', color: 'bg-indigo-500', total_value: 2000000, count: 1 },
  { id: 6, name: '贵金属', icon: 'DollarSign', color: 'bg-yellow-500', total_value: 30000, count: 2 },
  { id: 7, name: '期货', icon: 'TrendingUp', color: 'bg-red-500', total_value: 45000, count: 3 },
  { id: 8, name: '外汇', icon: 'DollarSign', color: 'bg-teal-500', total_value: 15000, count: 2 }
]

const mockAssets: Asset[] = [
  {
    id: 1, name: '苹果公司', symbol: 'AAPL', category_id: 1, category_name: '股票',
    quantity: 100, purchase_price: 150, current_price: 180, purchase_date: '2024-01-15',
    total_value: 18000, profit_loss: 3000, profit_loss_percentage: 20, notes: '科技股长期持有',
    balance: 18000, status: 'active'
  },
  {
    id: 2, name: '特斯拉', symbol: 'TSLA', category_id: 1, category_name: '股票',
    quantity: 50, purchase_price: 200, current_price: 250, purchase_date: '2024-02-10',
    total_value: 12500, profit_loss: 2500, profit_loss_percentage: 25,
    balance: 12500, status: 'active'
  },
  {
    id: 3, name: '微软', symbol: 'MSFT', category_id: 1, category_name: '股票',
    quantity: 80, purchase_price: 300, current_price: 350, purchase_date: '2024-01-20',
    total_value: 28000, profit_loss: 4000, profit_loss_percentage: 16.67,
    balance: 28000, status: 'active'
  },
  {
    id: 4, name: '谷歌', symbol: 'GOOGL', category_id: 1, category_name: '股票',
    quantity: 30, purchase_price: 2500, current_price: 2700, purchase_date: '2024-03-05',
    total_value: 81000, profit_loss: 6000, profit_loss_percentage: 8,
    balance: 81000, status: 'active'
  },
  {
    id: 5, name: '亚马逊', symbol: 'AMZN', category_id: 1, category_name: '股票',
    quantity: 25, purchase_price: 120, current_price: 140, purchase_date: '2024-02-28',
    total_value: 3500, profit_loss: 500, profit_loss_percentage: 16.67,
    balance: 3500, status: 'inactive'
  },
  {
    id: 6, name: '沪深300ETF', symbol: '510300', category_id: 2, category_name: '基金',
    quantity: 10000, purchase_price: 4.2, current_price: 4.5, purchase_date: '2024-01-10',
    total_value: 45000, profit_loss: 3000, profit_loss_percentage: 7.14,
    balance: 45000, status: 'active'
  },
  {
    id: 7, name: '中证500ETF', symbol: '510500', category_id: 2, category_name: '基金',
    quantity: 5000, purchase_price: 6.8, current_price: 7.2, purchase_date: '2024-02-15',
    total_value: 36000, profit_loss: 2000, profit_loss_percentage: 5.88,
    balance: 36000, status: 'active'
  },
  {
    id: 8, name: '比特币', symbol: 'BTC', category_id: 3, category_name: '加密货币',
    quantity: 0.5, purchase_price: 40000, current_price: 45000, purchase_date: '2024-03-01',
    total_value: 22500, profit_loss: 2500, profit_loss_percentage: 12.5,
    balance: 22500, status: 'active'
  },
  {
    id: 9, name: '以太坊', symbol: 'ETH', category_id: 3, category_name: '加密货币',
    quantity: 5, purchase_price: 2500, current_price: 2800, purchase_date: '2024-03-10',
    total_value: 14000, profit_loss: 1500, profit_loss_percentage: 12,
    balance: 14000, status: 'active'
  },
  {
    id: 10, name: '美国10年期国债', symbol: 'US10Y', category_id: 4, category_name: '债券',
    quantity: 1000, purchase_price: 98, current_price: 99.5, purchase_date: '2024-01-05',
    total_value: 99500, profit_loss: 1500, profit_loss_percentage: 1.53,
    balance: 99500, status: 'active'
  },
  {
    id: 11, name: '黄金ETF', symbol: 'GLD', category_id: 6, category_name: '贵金属',
    quantity: 100, purchase_price: 180, current_price: 185, purchase_date: '2024-02-20',
    total_value: 18500, profit_loss: 500, profit_loss_percentage: 2.78,
    balance: 18500, status: 'active'
  },
  {
    id: 12, name: '白银期货', symbol: 'SI', category_id: 7, category_name: '期货',
    quantity: 10, purchase_price: 25, current_price: 27, purchase_date: '2024-03-15',
    total_value: 270, profit_loss: 20, profit_loss_percentage: 8,
    balance: 270, status: 'active'
  }
]

const mockTransactions: AssetTransaction[] = [
  {
    id: 1, asset_id: 1, asset_name: '苹果公司', asset_symbol: 'AAPL',
    transaction_type: 'buy', quantity: 50, price: 175, total_amount: 8750,
    transaction_date: '2024-12-01', notes: '逢低买入', balance_after: 18000
  },
  {
    id: 2, asset_id: 2, asset_name: '特斯拉', asset_symbol: 'TSLA',
    transaction_type: 'sell', quantity: 20, price: 260, total_amount: 5200,
    transaction_date: '2024-12-02', notes: '部分获利了结', balance_after: 7300
  },
  {
    id: 3, asset_id: 6, asset_name: '沪深300ETF', asset_symbol: '510300',
    transaction_type: 'dividend', quantity: 0, price: 0, total_amount: 450,
    transaction_date: '2024-12-03', notes: '季度分红', balance_after: 45450
  },
  {
    id: 4, asset_id: 8, asset_name: '比特币', asset_symbol: 'BTC',
    transaction_type: 'buy', quantity: 0.1, price: 42000, total_amount: 4200,
    transaction_date: '2024-12-04', notes: '定投', balance_after: 26700
  }
]

function AssetsPage() {
  // 认证状态
  const { user, token } = useAuth()
  const [showLoginModal, setShowLoginModal] = useState(false)
  
  const [categories] = useState<AssetCategory[]>(mockCategories)
  const [assets] = useState<Asset[]>(mockAssets)
  const [portfolioOverview, setPortfolioOverview] = useState<PortfolioOverview | null>(null)
  const [revenueTrend, setRevenueTrend] = useState<RevenueTrendData | null>(null)
  const [expenseTrend, setExpenseTrend] = useState<ExpenseTrendData | null>(null)
  const [isLoadingOverview, setIsLoadingOverview] = useState(true)
  const [isLoadingRevenue, setIsLoadingRevenue] = useState(true)
  const [isLoadingExpense, setIsLoadingExpense] = useState(true)
  const [selectedCategory, setSelectedCategory] = useState<number | 'all'>('all')
  const [isAddCategoryOpen, setIsAddCategoryOpen] = useState(false)
  const [searchTerm, setSearchTerm] = useState('')

  
  // 交易明细相关状态
  const [transactions, setTransactions] = useState<AssetTransaction[]>(mockTransactions)
  const [selectedAsset, setSelectedAsset] = useState<number | 'all'>('all')
  const [dateFrom, setDateFrom] = useState('')
  const [dateTo, setDateTo] = useState('')
  const [currentPage, setCurrentPage] = useState(1)
  const [itemsPerPage] = useState(10)
  const [shareModalOpen, setShareModalOpen] = useState(false)
  const [selectedTransaction, setSelectedTransaction] = useState<AssetTransaction | null>(null)
  const [isAddTransactionOpen, setIsAddTransactionOpen] = useState(false)

  const handleDeleteTransaction = useCallback((id: number) => {
    setTransactions(prev => prev.filter(t => t.id !== id))
  }, [])
  
  // 分层眼睛控制状态
  const [showTotalProfit, setShowTotalProfit] = useState(() => {
    const saved = localStorage.getItem('showTotalProfit')
    return saved !== null ? JSON.parse(saved) : false
  })
  const [showYesterdayChange, setShowYesterdayChange] = useState(() => {
    const saved = localStorage.getItem('showYesterdayChange')
    return saved !== null ? JSON.parse(saved) : false
  })
  
  // 编辑总盈亏金额的状态
  const [isEditTotalProfitOpen, setIsEditTotalProfitOpen] = useState(false)
  const [newTotalProfitAmount, setNewTotalProfitAmount] = useState('')
  
  // 收益和支出添加相关状态
  const [isAddRevenueOpen, setIsAddRevenueOpen] = useState(false)
  const [isAddExpenseOpen, setIsAddExpenseOpen] = useState(false)
  
  // 数据统计相关状态
  const [selectedTimeline, setSelectedTimeline] = useState<5 | 10 | 20 | 30>(5)
  const [selectedExpenseTimeline, setSelectedExpenseTimeline] = useState<5 | 10 | 20 | 30>(5)
  
  // 检测是否为手机端
  const [isMobile, setIsMobile] = useState(() => {
    if (typeof window !== 'undefined') {
      return window.innerWidth < 640
    }
    return false
  })
  
  // 监听窗口大小变化
  useEffect(() => {
    const handleResize = () => {
      setIsMobile(window.innerWidth < 640)
    }
    
    window.addEventListener('resize', handleResize)
    return () => window.removeEventListener('resize', handleResize)
  }, [])
  
  // 支出和收益汇总的眼睛控制状态
  const [showExpenseSummary, setShowExpenseSummary] = useState(() => {
    const saved = localStorage.getItem('showExpenseSummary')
    return saved !== null ? JSON.parse(saved) : false
  })
  const [showRevenueSummary, setShowRevenueSummary] = useState(() => {
    const saved = localStorage.getItem('showRevenueSummary')
    return saved !== null ? JSON.parse(saved) : false
  })
  
  // 加载投资组合数据
  const loadPortfolioOverview = useCallback(async () => {
    if (!token) return // 如果没有令牌，不执行请求
    
    setIsLoadingOverview(true)
    try {
      const response = await assetService.getPortfolioOverview()
      if (response.success && response.data) {
        setPortfolioOverview(response.data)
      } else {
        console.error('获取投资组合数据失败:', response.message)
      }
    } catch (error) {
      console.error('加载投资组合数据错误:', error)
    } finally {
      setIsLoadingOverview(false)
    }
  }, [token])
  
  // 加载收益趋势数据
  const loadRevenueTrend = useCallback(async (days: number) => {
    if (!token) return // 如果没有令牌，不执行请求
    
    setIsLoadingRevenue(true)
    try {
      const response = await assetService.getRevenueTrend(days)
      if (response.success && response.data) {
        setRevenueTrend(response.data)
      } else {
        console.error('获取收益趋势数据失败:', response.message)
      }
    } catch (error) {
      console.error('加载收益趋势数据错误:', error)
    } finally {
      setIsLoadingRevenue(false)
    }
  }, [token])
  
  // 加载支出趋势数据
  const loadExpenseTrend = useCallback(async (days: number) => {
    if (!token) return // 如果没有令牌，不执行请求
    
    setIsLoadingExpense(true)
    try {
      const response = await assetService.getExpenseTrend(days)
      if (response.success && response.data) {
        setExpenseTrend(response.data)
      } else {
        console.error('获取支出趋势数据失败:', response.message)
      }
    } catch (error) {
      console.error('加载支出趋势数据错误:', error)
    } finally {
      setIsLoadingExpense(false)
    }
  }, [token])
  
  // 调整投资组合总金额
  const adjustPortfolioTotalAmount = useCallback(async () => {
    if (!newTotalProfitAmount) return
    
    try {
      const amount = parseFloat(newTotalProfitAmount)
      if (isNaN(amount)) {
        console.error('请输入有效的金额')
        return
      }
      
      const response = await assetService.adjustPortfolioTotalAmount(amount)
      
      if (response.success) {
        // 更新成功后重新加载数据
        await loadPortfolioOverview()
        setIsEditTotalProfitOpen(false)
        setNewTotalProfitAmount('')
      } else {
        console.error('调整失败:', response.message)
      }
    } catch (error) {
      console.error('调整投资组合总金额错误:', error)
    }
  }, [newTotalProfitAmount, loadPortfolioOverview])

  // 添加收益
  const addRevenue = useCallback(async (amount: number) => {
    try {
      if (isNaN(amount)) {
        return
      }
      
      const response = await assetService.addRevenue(amount)
      
      if (response.success) {
        // 更新成功后重新加载数据
        await loadRevenueTrend(selectedTimeline)
        await loadPortfolioOverview() // 重新加载投资组合概览数据
        setIsAddRevenueOpen(false)
      } else {
        console.error('添加收益失败:', response.message)
      }
    } catch (error) {
      console.error('添加收益错误:', error)
    }
  }, [selectedTimeline, loadRevenueTrend, loadPortfolioOverview])

  // 添加支出
  const addExpense = useCallback(async (amount: number) => {
    try {
      if (isNaN(amount)) {
        return
      }
      
      const response = await assetService.addExpense(amount)
      
      if (response.success) {
        // 更新成功后重新加载数据
        await loadExpenseTrend(selectedExpenseTimeline)
        setIsAddExpenseOpen(false)
      } else {
        console.error('添加支出失败:', response.message)
      }
    } catch (error) {
      console.error('添加支出错误:', error)
    }
  }, [selectedExpenseTimeline, loadExpenseTrend])
  
  // 交易明细过滤和分页
  const filteredTransactions = useMemo(() => {
    let filtered = transactions
    
    // 资产过滤
    if (selectedAsset !== 'all') {
      filtered = filtered.filter(transaction => transaction.asset_id === selectedAsset)
    }
    
    // 搜索过滤
    if (searchTerm) {
      const searchLower = searchTerm.toLowerCase()
      filtered = filtered.filter(transaction => 
        transaction.asset_name.toLowerCase().includes(searchLower) ||
        transaction.asset_symbol.toLowerCase().includes(searchLower)
      )
    }
    
    // 日期过滤
    if (dateFrom) {
      filtered = filtered.filter(transaction => transaction.transaction_date >= dateFrom)
    }
    if (dateTo) {
      filtered = filtered.filter(transaction => transaction.transaction_date <= dateTo)
    }
    
    // 排序（按日期倒序）
    filtered.sort((a, b) => new Date(b.transaction_date).getTime() - new Date(a.transaction_date).getTime())
    
    return filtered
  }, [transactions, selectedAsset, searchTerm, dateFrom, dateTo])
  
  // 分页
  const paginatedTransactions = useMemo(() => {
    const startIndex = (currentPage - 1) * itemsPerPage
    return filteredTransactions.slice(startIndex, startIndex + itemsPerPage)
  }, [filteredTransactions, currentPage, itemsPerPage])
  
  const totalPages = Math.ceil(filteredTransactions.length / itemsPerPage)

  // 格式化货币
  const formatCurrency = useCallback((amount: number, localShow?: boolean) => {
    // 如果传入了localShow参数，使用该参数；否则默认显示
    const shouldShow = localShow !== undefined ? localShow : true
    if (!shouldShow) return '****'
    return new Intl.NumberFormat('zh-CN', {
      style: 'currency',
      currency: 'CNY'
    }).format(amount)
  }, [])

  // 格式化数量（用于资产列表）
  const formatQuantity = useCallback((quantity: number) => {
    return quantity.toString()
  }, [])
  
  // 处理趋势数据用于图表显示
  const processTrendData = useCallback((data: RevenueTrendData | ExpenseTrendData | null) => {
    if (!data || !data.list) return []
    
    // 按日期排序
    const sortedList = [...data.list].sort((a, b) => 
      new Date(a.created_at).getTime() - new Date(b.created_at).getTime()
    )
    
    return sortedList.map(item => ({
      date: item.created_at.split(' ')[0], // 只取日期部分
      amount: parseFloat(item.amount),
      formattedDate: new Date(item.created_at).toLocaleDateString('zh-CN', { 
        month: 'numeric', 
        day: 'numeric' 
      })
    }))
  }, [])

  // 初始化加载数据 - 只在有认证令牌时加载
  useEffect(() => {
    if (token) {
      loadPortfolioOverview()
      loadRevenueTrend(5) // 默认加载5天数据
      loadExpenseTrend(5) // 默认加载5天数据
    } else {
      // 如果没有认证令牌，清空数据
      setPortfolioOverview(null)
      setRevenueTrend(null)
      setExpenseTrend(null)
    }
  }, [token, loadPortfolioOverview, loadRevenueTrend, loadExpenseTrend])

  // 如果用户未登录，显示登录提示
  if (!user || !token) {
    return (
      <div className="min-h-screen flex items-center justify-center p-4">
        <Card className="w-full max-w-md">
          <CardHeader className="text-center">
            <div className="mx-auto w-12 h-12 bg-gray-100 dark:bg-gray-800 rounded-full flex items-center justify-center mb-4">
              <Lock className="w-6 h-6 text-gray-600 dark:text-gray-400" />
            </div>
            <CardTitle className="text-xl">需要登录</CardTitle>
            <CardDescription>
              请先登录以查看资产管理功能
            </CardDescription>
          </CardHeader>
          <CardContent>
            <Button 
              className="w-full" 
              onClick={() => setShowLoginModal(true)}
            >
              立即登录
            </Button>
          </CardContent>
        </Card>
      </div>
    )
  }

  return (
    <div className="p-2 sm:p-4 md:p-6 space-y-4 sm:space-y-6">
      {/* 主要内容区域 */}
      <Tabs defaultValue="stats" className="space-y-6">
        <TabsList className="grid w-full grid-cols-2 h-12 p-1 bg-muted rounded-lg">
          <TabsTrigger value="stats" className="h-10 text-sm font-medium data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-sm">数据统计</TabsTrigger>
          <TabsTrigger value="assets" className="h-10 text-sm font-medium data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-sm">资产管理</TabsTrigger>
        </TabsList>
        
        <TabsContent value="assets" className="space-y-6">
          {/* 资产分类 */}
          <Card>
            <CardHeader className="flex flex-row items-center justify-between">
              <CardTitle>资产分类</CardTitle>
              <Dialog open={isAddCategoryOpen} onOpenChange={setIsAddCategoryOpen}>
                <DialogTrigger asChild>
                  <Button size="sm">
                    <Plus className="h-4 w-4 mr-2" />
                    添加分类
                  </Button>
                </DialogTrigger>
                <DialogContent>
                  <DialogHeader>
                    <DialogTitle>添加资产分类</DialogTitle>
                  </DialogHeader>
                  <AddCategoryForm onClose={() => setIsAddCategoryOpen(false)} />
                </DialogContent>
              </Dialog>
            </CardHeader>
            <CardContent>
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                <Card 
                  className={cn(
                    "cursor-pointer transition-colors hover:bg-muted/50",
                    selectedCategory === 'all' ? "ring-2 ring-primary" : ""
                  )}
                  onClick={() => setSelectedCategory('all')}
                >
                  <CardContent className="p-4">
                    <div className="flex items-center justify-between">
                      <div className="flex items-center gap-3">
                        <div className="p-2 rounded-lg bg-gray-500">
                          <DollarSign className="h-4 w-4 text-white" />
                        </div>
                        <div>
                          <h3 className="font-semibold">全部资产</h3>
                          <p className="text-sm text-muted-foreground">
                            {categories.reduce((sum, cat) => sum + cat.count, 0)} 项资产
                          </p>
                        </div>
                      </div>
                      <div className="text-right">
                        <p className="text-lg font-bold">
                          {formatCurrency(categories.reduce((sum, cat) => sum + cat.total_value, 0))}
                        </p>
                      </div>
                    </div>
                  </CardContent>
                </Card>
                {categories.map((category) => (
                  <Card 
                    key={category.id}
                    className={cn(
                      "cursor-pointer transition-colors hover:bg-muted/50",
                      selectedCategory === category.id ? "ring-2 ring-primary" : ""
                    )}
                    onClick={() => setSelectedCategory(category.id)}
                  >
                    <CardContent className="p-4">
                      <div className="flex items-center justify-between">
                        <div className="flex items-center gap-3">
                          <div className={cn("p-2 rounded-lg", category.color)}>
                            <TrendingUp className="h-4 w-4 text-white" />
                          </div>
                          <div>
                            <h3 className="font-semibold">{category.name}</h3>
                            <p className="text-sm text-muted-foreground">{category.count} 项资产</p>
                          </div>
                        </div>
                        <div className="text-right">
                          <p className="text-lg font-bold">{formatCurrency(category.total_value)}</p>
                        </div>
                      </div>
                    </CardContent>
                  </Card>
                ))}
              </div>
            </CardContent>
          </Card>

          {/* 资产变动明细 */}
          <Card>
            <CardHeader className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
              <CardTitle>资产变动明细</CardTitle>
              <div className="flex flex-col sm:flex-row items-stretch sm:items-center gap-2">
                <div className="relative">
                  <Search className="h-4 w-4 absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground" />
                  <Input
                    placeholder="搜索资产..."
                    value={searchTerm}
                    onChange={(e) => setSearchTerm(e.target.value)}
                    className="pl-9 w-full sm:w-48"
                  />
                </div>
                <Select value={selectedAsset.toString()} onValueChange={(value) => setSelectedAsset(value === 'all' ? 'all' : parseInt(value))}>
                  <SelectTrigger className="w-40">
                    <SelectValue placeholder="选择资产" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">全部资产</SelectItem>
                    {assets.map(asset => (
                      <SelectItem key={asset.id} value={asset.id.toString()}>{asset.name}</SelectItem>
                    ))}
                  </SelectContent>
                </Select>
                <Input
                  type="date"
                  value={dateFrom}
                  onChange={(e) => setDateFrom(e.target.value)}
                  className="w-32"
                />
                <span className="text-sm text-muted-foreground">至</span>
                <Input
                  type="date"
                  value={dateTo}
                  onChange={(e) => setDateTo(e.target.value)}
                  className="w-32"
                />
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => {
                    setSearchTerm('')
                    setSelectedAsset('all')
                    setDateFrom('')
                    setDateTo('')
                  }}
                >
                  重置
                </Button>
                <Button size="sm" onClick={() => setIsAddTransactionOpen(true)}>
                  <Plus className="h-4 w-4 mr-2" /> 添加明细
                </Button>
              </div>
            </CardHeader>
            <CardContent>
              {paginatedTransactions.length === 0 ? (
                <div className="text-center py-8 text-muted-foreground">
                  暂无交易记录
                </div>
              ) : (
                <>
                  {/* 桌面端表格 */}
                  <div className="hidden md:block">
                    <Table>
                      <TableHeader>
                        <TableRow>
                          <TableHead>交易时间</TableHead>
                          <TableHead>资产名称</TableHead>
                          <TableHead className="text-right">价格</TableHead>
                          <TableHead>备注</TableHead>
                          <TableHead className="text-center">操作</TableHead>
                        </TableRow>
                      </TableHeader>
                      <TableBody>
                        {paginatedTransactions.map((transaction) => {
                          const asset = assets.find(a => a.id === transaction.asset_id)
                          const category = categories.find(c => c.id === asset?.category_id)
                          
                          return (
                            <TableRow key={transaction.id}>
                              <TableCell>{transaction.transaction_date}</TableCell>
                              <TableCell>
                                <div className="flex items-center gap-2">
                                  <div className={`w-3 h-3 rounded-full ${category?.color || 'bg-gray-400'}`}></div>
                                  <span className="font-medium">{asset?.name || '未知资产'}</span>
                                </div>
                              </TableCell>
                              <TableCell className="text-right">{formatCurrency(transaction.price)}</TableCell>
                              <TableCell className="max-w-xs truncate">{transaction.notes || '-'}</TableCell>
                              <TableCell>
                                <div className="flex items-center justify-center gap-2">
                                  <Button
                                    variant="ghost"
                                    size="sm"
                                    onClick={() => { setSelectedTransaction(transaction); setShareModalOpen(true) }}
                                  >
                                    <Share2 className="h-4 w-4" />
                                  </Button>
                                  <Button
                                    variant="ghost"
                                    size="sm"
                                    onClick={() => handleDeleteTransaction(transaction.id)}
                                  >
                                    删除
                                  </Button>
                                </div>
                              </TableCell>
                            </TableRow>
                          )
                        })}
                      </TableBody>
                    </Table>
                    {totalPages > 1 && (
                      <div className="hidden md:flex justify-end items-center gap-2 mt-4">
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => setCurrentPage(Math.max(1, currentPage - 1))}
                          disabled={currentPage === 1}
                        >
                          上一页
                        </Button>
                        <span className="text-sm text-muted-foreground">第 {currentPage} 页，共 {totalPages} 页</span>
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => setCurrentPage(Math.min(totalPages, currentPage + 1))}
                          disabled={currentPage === totalPages}
                        >
                          下一页
                        </Button>
                      </div>
                    )}
                  </div>
              
              {/* 移动端卡片列表 */}
              <div className="md:hidden space-y-4">
                {paginatedTransactions.map((transaction) => {
                  const asset = assets.find(a => a.id === transaction.asset_id)
                  const category = categories.find(c => c.id === asset?.category_id)
                  
                  return (
                    <Card key={transaction.id} className="p-4">
                      <div className="space-y-3">
                        {/* 交易基本信息 */}
                        <div className="flex items-start justify-between">
                          <div className="flex-1">
                            <h3 className="font-medium text-base">{asset?.name || '未知资产'}</h3>
                            <div className="flex items-center gap-2 mt-1">
                              <span className="text-sm text-muted-foreground">{transaction.transaction_date}</span>
                            </div>
                          </div>
                          <div className="flex gap-1">
                            <Button 
                              size="sm" 
                              variant="outline"
                              onClick={() => setSelectedTransaction(transaction)}
                            >
                              <Share2 className="h-3 w-3" />
                            </Button>
                          </div>
                        </div>
                        
                        {/* 交易数据 */}
                        <div className="grid grid-cols-2 gap-3 text-sm">
                          <div>
                            <span className="text-muted-foreground">价格</span>
                            <p className="font-medium">{formatCurrency(transaction.price)}</p>
                          </div>
                          <div className="text-right">
                            <span className="text-muted-foreground">资产分类</span>
                            <p className="font-medium">{category?.name || '未分类'}</p>
                          </div>
                        </div>
                        
                        {/* 备注信息 */}
                        {transaction.notes && (
                          <div className="pt-2 border-t">
                            <span className="text-sm text-muted-foreground">备注</span>
                            <p className="text-sm">{transaction.notes}</p>
                          </div>
                        )}
                      </div>
                    </Card>
                  )
                })}
              </div>
              
              {/* 分页 */}
              {totalPages > 1 && (
                <div className="flex justify-center items-center gap-2 mt-6">
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => setCurrentPage(Math.max(1, currentPage - 1))}
                    disabled={currentPage === 1}
                  >
                    上一页
                  </Button>
                  <span className="text-sm text-muted-foreground">
                    第 {currentPage} 页，共 {totalPages} 页
                  </span>
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => setCurrentPage(Math.min(totalPages, currentPage + 1))}
                    disabled={currentPage === totalPages}
                  >
                    下一页
                  </Button>
                </div>
              )}
            </>
          )}
            </CardContent>
          </Card>
        </TabsContent>
        
        <TabsContent value="stats" className="space-y-6">
          {/* 投资组合概览 */}
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <PieChart className="h-5 w-5" />
                投资组合概览
              </CardTitle>
            </CardHeader>
            <CardContent>
              {isLoadingOverview ? (
                <div className="flex items-center justify-center h-24">
                  <div className="text-muted-foreground">加载中...</div>
                </div>
              ) : portfolioOverview ? (
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  {/* 1. 总盈亏 */}
                  <div className="space-y-2">
                    <div className="flex items-center gap-2">
                      <p className="text-sm text-muted-foreground">总盈亏</p>
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => {
                          const newValue = !showTotalProfit
                          setShowTotalProfit(newValue)
                          localStorage.setItem('showTotalProfit', JSON.stringify(newValue))
                        }}
                        className="h-6 w-6 p-0"
                      >
                        {showTotalProfit ? (
                          <Eye className="h-4 w-4 dark:invert" />
                        ) : (
                          <EyeOff className="h-4 w-4 dark:invert" />
                        )}
                      </Button>
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => {
                          setNewTotalProfitAmount('')
                          setIsEditTotalProfitOpen(true)
                        }}
                        className="h-6 w-6 p-0"
                      >
                        <Edit className="h-4 w-4" />
                      </Button>
                    </div>
                    <p className={cn(
                      "text-2xl font-bold",
                      (portfolioOverview.total_value ?? 0) >= 0 ? "text-green-600" : "text-red-600"
                    )}>
                      {formatCurrency(portfolioOverview.total_value ?? 0, showTotalProfit)}
                    </p>
                  </div>
                </div>
              ) : (
                <div className="flex items-center justify-center h-24">
                  <div className="text-muted-foreground">暂无数据</div>
                </div>
              )}
            </CardContent>
          </Card>

          {/* 收益走势 */}
          <Card>
            <CardHeader className="flex flex-col space-y-4 sm:flex-row sm:items-center sm:justify-between sm:space-y-0">
              <CardTitle className="flex items-center gap-2">
                <BarChart3 className="h-5 w-5 text-green-500" />
                收益走势
                <Button
                  variant="default"
                  size="sm"
                  onClick={() => setIsAddRevenueOpen(true)}
                  className="h-6 w-6 p-0 ml-2"
                >
                  <Plus className="h-4 w-4" />
                </Button>
              </CardTitle>
              <div className="flex flex-col space-y-2 sm:space-y-0 sm:flex-row sm:items-center sm:gap-2">
                <span className="text-sm text-muted-foreground">时间范围:</span>
                <div className="grid grid-cols-2 gap-2 sm:flex sm:gap-2">
                  {(() => {
                    // 手机端只显示5天和10天，桌面端显示全部
                    const options = isMobile ? [5, 10] : [5, 10, 20, 30]
                    return options.map((days) => (
                      <Button
                        key={days}
                        variant={selectedTimeline === days ? "default" : "outline"}
                        size="sm"
                        onClick={() => setSelectedTimeline(days as 5 | 10 | 20 | 30)}
                        className="min-w-[60px]"
                      >
                        {days}天
                      </Button>
                    ))
                  })()}
                </div>
              </div>
            </CardHeader>
            <CardContent>
              {isLoadingRevenue ? (
                <div className="flex items-center justify-center h-64">
                  <div className="text-muted-foreground">加载中...</div>
                </div>
              ) : revenueTrend ? (
                <>
                  {/* 收益走势柱状图 */}
                  <div className="h-40 sm:h-48 relative">
                    {(() => {
                      const processedData = processTrendData(revenueTrend)
                      if (processedData.length === 0) {
                        return (
                          <div className="flex items-center justify-center h-full">
                            <div className="text-muted-foreground">暂无数据</div>
                          </div>
                        )
                      }
                      
                      // 计算最大值和最小值
                      const amounts = processedData.map(d => d.amount)
                      const maxValue = Math.max(...amounts, 0)
                      const minValue = Math.min(...amounts, 0)
                      const hasNegative = minValue < 0
                      const hasPositive = maxValue > 0
                      
                      return (
                        <>
                          <div className="h-full flex items-center justify-center px-1 relative">
                            {/* 零基线 - 作为绿柱和红柱的分界线 */}
                            <div 
                              className="absolute w-full h-[1px] bg-gray-400 dark:bg-gray-500 left-0 flex items-center z-20" 
                              style={{top: '50%', transform: 'translateY(-50%)'}}
                            >
                              <span className="text-xs text-gray-600 dark:text-gray-400 bg-white dark:bg-gray-900 px-1.5 py-0.5 -ml-1 font-medium border border-gray-300 dark:border-gray-600 rounded-sm">
                                0
                              </span>
                            </div>
                            {processedData.map((item, index) => {
                              const isPositive = item.amount >= 0
                              const totalRange = maxValue - minValue
                              const chartHeight = 160 // 使用像素值而不是百分比
                              
                              // 计算柱子高度（相对于零基线）
                              let barHeight = 0
                              if (hasNegative && hasPositive) {
                                // 有正负值：按数据范围计算
                                barHeight = Math.abs(item.amount) / totalRange * chartHeight * 0.8
                              } else {
                                // 只有正值或负值：全量程计算
                                const maxAbsValue = Math.max(Math.abs(maxValue), Math.abs(minValue))
                                barHeight = Math.abs(item.amount) / maxAbsValue * chartHeight * 0.9
                              }
                              
                              barHeight = Math.max(barHeight, 4) // 最小4px高度
                              const barWidth = Math.max(100 / processedData.length - 1, 8) // 柱子宽度
                              
                              return (
                                <div key={index} className="flex-1 flex flex-col items-center mx-[0.5px] h-full relative">
                                  {/* 上半部分：从中间向上 - 正值绿柱 */}
                                  <div className="flex-1 flex items-end justify-center">
                                    {isPositive && item.amount !== 0 && (
                                      <div 
                                        className="bg-green-500 transition-opacity hover:opacity-80 relative group"
                                        style={{
                                          height: `${Math.min(barHeight, 80)}px`,
                                          width: `${barWidth}px`
                                        }}
                                      >
                                        {/* 悬停提示 */}
                                        <div className="absolute bottom-full left-1/2 transform -translate-x-1/2 mb-2 px-2 py-1 bg-black text-white text-xs rounded opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none whitespace-nowrap z-30">
                                          {formatCurrency(item.amount)}
                                        </div>
                                      </div>
                                    )}
                                  </div>
                                  
                                  {/* 下半部分：从中间向下 - 负值红柱 */}
                                  <div className="flex-1 flex items-start justify-center">
                                    {!isPositive && item.amount !== 0 && (
                                      <div 
                                        className="bg-red-500 transition-opacity hover:opacity-80 relative group"
                                        style={{
                                          height: `${Math.min(barHeight, 80)}px`,
                                          width: `${barWidth}px`
                                        }}
                                      >
                                        <div className="absolute top-full left-1/2 transform -translate-x-1/2 mt-2 px-2 py-1 bg-black text-white text-xs rounded opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none whitespace-nowrap z-30">
                                          {formatCurrency(item.amount)}
                                        </div>
                                      </div>
                                    )}
                                  </div>
                                </div>
                              )
                            })}
                          </div>
                        </>
                      )
                    })()}
                  </div>
                  
                  {/* 日期标签 */}
                  <div className="flex px-1 mt-2">
                    {(() => {
                      const processedData = processTrendData(revenueTrend)
                      if (processedData.length === 0) return null
                      
                      return processedData.map((item, index) => {
                        // 显示所有日期
                        const shouldShow = true
                        
                        return (
                          <div key={index} className="flex-1 flex justify-center mx-[0.5px]">
                            {shouldShow && (
                              <span className="text-xs text-gray-500 origin-center text-[10px] sm:text-xs inline-block leading-none">
                                {new Date(item.date).toLocaleDateString('zh-CN', { month: 'numeric', day: 'numeric' })}
                              </span>
                            )}
                          </div>
                        )
                      })
                    })()}
                  </div>
                  
                  {/* 数据汇总 */}
                  <div className="bg-gray-50 dark:bg-gray-900/50 dark:border dark:border-gray-800 rounded-lg p-3 mt-4">
                    <div className="flex items-center gap-2 mb-2">
                      <span className="text-sm font-medium text-gray-700 dark:text-gray-300">收益汇总</span>
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => {
                          const newValue = !showRevenueSummary
                          setShowRevenueSummary(newValue)
                          localStorage.setItem('showRevenueSummary', JSON.stringify(newValue))
                        }}
                        className="h-6 w-6 p-0"
                      >
                        {showRevenueSummary ? (
                          <Eye className="h-4 w-4 dark:invert" />
                        ) : (
                          <EyeOff className="h-4 w-4 dark:invert" />
                        )}
                      </Button>
                    </div>
                    <div className="grid grid-cols-3 gap-4">
                      <div>
                        <p className="text-xs text-gray-500">当日总额</p>
                        <p className={`text-lg font-bold ${((revenueTrend?.today || 0) >= 0 ? 'text-green-600' : 'text-red-600')}`}>
                          {showRevenueSummary ? (
                            ((revenueTrend?.today || 0) >= 0 ? '+' : '') + formatCurrency(revenueTrend?.today || 0)
                          ) : '****'}
                        </p>
                      </div>
                      <div>
                        <p className="text-xs text-gray-500">{selectedTimeline}天总额</p>
                        <p className={`text-lg font-bold ${((revenueTrend?.total || 0) >= 0 ? 'text-green-600' : 'text-red-600')}`}>
                          {showRevenueSummary ? (
                            ((revenueTrend?.total || 0) >= 0 ? '+' : '') + formatCurrency(revenueTrend?.total || 0)
                          ) : '****'}
                        </p>
                      </div>
                      <div>
                        <p className="text-xs text-gray-500">{selectedTimeline}平均额</p>
                        <p className={`text-lg font-bold ${((parseFloat(revenueTrend?.average || '0') || 0) >= 0 ? 'text-green-600' : 'text-red-600')}`}>
                          {showRevenueSummary ? (
                            ((parseFloat(revenueTrend?.average || '0') || 0) >= 0 ? '+' : '') + formatCurrency(parseFloat(revenueTrend?.average || '0') || 0)
                          ) : '****'}
                        </p>
                      </div>
                    </div>
                  </div>
                  
                  {/* 图例 */}
                  <div className="flex justify-center space-x-4 mt-2">
                    <div className="flex items-center space-x-1">
                      <div className="w-3 h-2 bg-green-500 rounded-sm"></div>
                      <span className="text-xs text-gray-600">盈利</span>
                    </div>
                    <div className="flex items-center space-x-1">
                      <div className="w-4 h-[1px] bg-gray-400 dark:bg-gray-500 rounded-sm"></div>
                      <span className="text-xs text-gray-600">零基线</span>
                    </div>
                    <div className="flex items-center space-x-1">
                      <div className="w-3 h-2 bg-red-500 rounded-sm"></div>
                      <span className="text-xs text-gray-600">亏损</span>
                    </div>
                  </div>
                </>
              ) : (
                <div className="flex items-center justify-center h-64">
                  <div className="text-muted-foreground">暂无数据</div>
                </div>
              )}
            </CardContent>
          </Card>
          
          {/* 支出走势 */}
          <Card>
            <CardHeader className="flex flex-col space-y-4 sm:flex-row sm:items-center sm:justify-between sm:space-y-0">
              <CardTitle className="flex items-center gap-2">
                <TrendingDown className="h-5 w-5 text-red-500" />
                支出走势
                <Button
                  variant="default"
                  size="sm"
                  onClick={() => setIsAddExpenseOpen(true)}
                  className="h-6 w-6 p-0 ml-2"
                >
                  <Plus className="h-4 w-4" />
                </Button>
              </CardTitle>
              <div className="flex flex-col space-y-2 sm:space-y-0 sm:flex-row sm:items-center sm:gap-2">
                <span className="text-sm text-muted-foreground">时间范围:</span>
                <div className="grid grid-cols-2 gap-2 sm:flex sm:gap-2">
                  {(() => {
                    // 手机端只显示5天和10天，桌面端显示全部
                    const options = isMobile ? [5, 10] : [5, 10, 20, 30]
                    return options.map((days) => (
                      <Button
                        key={days}
                        variant={selectedExpenseTimeline === days ? "default" : "outline"}
                        size="sm"
                        onClick={() => setSelectedExpenseTimeline(days as 5 | 10 | 20 | 30)}
                        className="min-w-[60px]"
                      >
                        {days}天
                      </Button>
                    ))
                  })()}
                </div>
              </div>
            </CardHeader>
            <CardContent>
              {isLoadingExpense ? (
                <div className="flex items-center justify-center h-64">
                  <div className="text-muted-foreground">加载中...</div>
                </div>
              ) : expenseTrend ? (
                <>
                  {/* 支出走势柱状图 */}
                  <div className="h-40 sm:h-48 relative">
                    {(() => {
                      const processedData = processTrendData(expenseTrend)
                      if (processedData.length === 0) {
                        return (
                          <div className="flex items-center justify-center h-full">
                            <div className="text-muted-foreground">暂无数据</div>
                          </div>
                        )
                      }
                      
                      // 计算最大值
                      const maxValue = Math.max(...processedData.map(d => d.amount), 0)
                      
                      return (
                        <div className="h-full flex items-end justify-center px-1">
                          {processedData.map((item, index) => {
                            const height = Math.max((item.amount / maxValue) * 85, 8)
                            return (
                              <div key={index} className="flex-1 flex flex-col items-center mx-[0.5px] h-full">
                                <div className="flex-1"></div>
                                {item.amount !== 0 && (
                                  <div className="relative group">
                                    <div
                                      className="bg-red-500 transition-opacity hover:opacity-80"
                                      style={{ 
                                        height: `${height * 0.01 * 160}px`,
                                        width: `${Math.max(100 / processedData.length - 0.5, 10)}px`
                                      }}
                                    ></div>
                                    <div className="absolute bottom-full left-1/2 transform -translate-x-1/2 mb-2 px-2 py-1 bg-black text-white text-xs rounded opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none whitespace-nowrap z-10">
                                      {formatCurrency(item.amount)}
                                    </div>
                                  </div>
                                )}
                              </div>
                            )
                          })}
                        </div>
                      )
                    })()}
                  </div>
                  
                  {/* 日期标签 */}
                  <div className="flex px-1 mt-2">
                    {(() => {
                      const processedData = processTrendData(expenseTrend)
                      if (processedData.length === 0) return null
                      
                      return processedData.map((item, index) => {
                        // 显示所有日期
                        const shouldShow = true
                        
                        return (
                          <div key={index} className="flex-1 flex justify-center mx-[0.5px]">
                            {shouldShow && (
                              <span className="text-xs text-gray-500 origin-center text-[10px] sm:text-xs inline-block leading-none">
                                {new Date(item.date).toLocaleDateString('zh-CN', { month: 'numeric', day: 'numeric' })}
                              </span>
                            )}
                          </div>
                        )
                      })
                    })()}
                  </div>
                  
                  {/* 数据汇总 */}
                  <div className="bg-gray-50 dark:bg-gray-900/50 dark:border dark:border-gray-800 rounded-lg p-3 mt-4">
                    <div className="flex items-center gap-2 mb-2">
                      <span className="text-sm font-medium text-gray-700 dark:text-gray-300">支出汇总</span>
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => {
                          const newValue = !showExpenseSummary
                          setShowExpenseSummary(newValue)
                          localStorage.setItem('showExpenseSummary', JSON.stringify(newValue))
                        }}
                        className="h-6 w-6 p-0"
                      >
                        {showExpenseSummary ? (
                          <Eye className="h-4 w-4 dark:invert" />
                        ) : (
                          <EyeOff className="h-4 w-4 dark:invert" />
                        )}
                      </Button>
                    </div>
                    <div className="grid grid-cols-3 gap-4">
                      <div>
                        <p className="text-xs text-gray-500">当日总额</p>
                        <p className="text-lg font-bold text-red-600">
                          {showExpenseSummary ? formatCurrency(expenseTrend?.today || 0) : '****'}
                        </p>
                      </div>
                      <div>
                        <p className="text-xs text-gray-500">{selectedExpenseTimeline}天总额</p>
                        <p className="text-lg font-bold text-red-600">
                          {showExpenseSummary ? formatCurrency(expenseTrend?.total || 0) : '****'}
                        </p>
                      </div>
                      <div>
                        <p className="text-xs text-gray-500">{selectedExpenseTimeline}平均额</p>
                        <p className="text-lg font-bold text-red-600">
                          {showExpenseSummary ? formatCurrency(parseFloat(expenseTrend?.average || '0') || 0) : '****'}
                        </p>
                      </div>
                    </div>
                  </div>
                  
                  {/* 图例 */}
                  <div className="flex justify-center space-x-4 mt-2">
                    <div className="flex items-center space-x-1">
                      <div className="w-3 h-2 bg-red-500 rounded-sm"></div>
                      <span className="text-xs text-gray-600">支出</span>
                    </div>
                  </div>
                </>
              ) : (
                <div className="flex items-center justify-center h-64">
                  <div className="text-muted-foreground">暂无数据</div>
                </div>
              )}
            </CardContent>
          </Card>
        </TabsContent>
        
      </Tabs>

      {/* 编辑总盈亏金额对话框 */}
      <Dialog open={isEditTotalProfitOpen} onOpenChange={setIsEditTotalProfitOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>调整总盈亏金额</DialogTitle>
          </DialogHeader>
          <div className="space-y-4">
            <div className="space-y-2">
              <Label htmlFor="total-profit-amount">调整金额</Label>
              <Input
                id="total-profit-amount"
                type="number"
                step="0.01"
                value={newTotalProfitAmount}
                onChange={(e) => setNewTotalProfitAmount(e.target.value)}
                placeholder="请输入调整金额，正数为增加，负数为减少"
              />
              <p className="text-sm text-muted-foreground">
                正数表示增加盈亏金额，负数表示减少盈亏金额
              </p>
            </div>
            <div className="flex gap-2">
              <Button onClick={adjustPortfolioTotalAmount} className="flex-1">
                确认调整
              </Button>
              <Button variant="outline" onClick={() => setIsEditTotalProfitOpen(false)} className="flex-1">
                取消
              </Button>
            </div>
          </div>
        </DialogContent>
      </Dialog>

      {/* 添加收益对话框 */}
      <AddRevenueDialog
        isOpen={isAddRevenueOpen}
        onClose={() => setIsAddRevenueOpen(false)}
        onAdd={addRevenue}
      />

      {/* 添加支出对话框 */}
      <AddExpenseDialog
        isOpen={isAddExpenseOpen}
        onClose={() => setIsAddExpenseOpen(false)}
        onAdd={addExpense}
      />
      
      {/* 登录对话框 */}
      <LoginModal 
        open={showLoginModal} 
        onClose={() => setShowLoginModal(false)} 
      />

      {/* 分享交易明细对话框 */}
      <ShareTransactionDialog
        transaction={selectedTransaction}
        isOpen={shareModalOpen}
        onClose={() => setShareModalOpen(false)}
        assets={assets}
        categories={categories}
      />
      {/* 添加明细对话框 */}
      <AddTransactionDialog
        isOpen={isAddTransactionOpen}
        onClose={() => setIsAddTransactionOpen(false)}
        assets={assets}
        onAdd={(payload) => {
          const asset = assets.find(a => a.id === payload.asset_id)
          if (!asset) return
          const newTx: AssetTransaction = {
            id: (transactions[0]?.id || 0) + 1,
            asset_id: asset.id,
            asset_name: asset.name,
            asset_symbol: asset.symbol,
            transaction_type: 'buy',
            quantity: 1,
            price: payload.price,
            total_amount: payload.price,
            transaction_date: payload.transaction_date,
            notes: payload.notes || ''
          }
          setTransactions(prev => [newTx, ...prev])
          setIsAddTransactionOpen(false)
        }}
      />
    </div>
  )
}

// 分享交易明细对话框
function ShareTransactionDialog({ 
  transaction, 
  isOpen, 
  onClose,
  assets,
  categories
}: { 
  transaction: AssetTransaction | null
  isOpen: boolean
  onClose: () => void
  assets: Asset[]
  categories: AssetCategory[]
}) {
  const [copied, setCopied] = useState(false)

  const generateShareText = () => {
    if (!transaction) return ''
    const asset = assets.find(a => a.id === transaction.asset_id)
    const category = categories.find(c => c.id === asset?.category_id)
    
    return `💰 资产交易记录

📊 ${asset?.name} (${asset?.symbol})
🏷️ 分类: ${category?.name || '未分类'}
📅 日期: ${transaction.transaction_date}
${transaction.transaction_type === 'buy' ? '🟢' : '🔴'} 类型: ${transaction.transaction_type === 'buy' ? '买入' : '卖出'}
📈 数量: ${transaction.quantity}
💵 价格: ¥${transaction.price}
💎 金额: ¥${transaction.quantity * transaction.price}
${transaction.notes ? `📝 备注: ${transaction.notes}` : ''}

#资产管理 #投资理财`
  }

  const handleCopy = async () => {
    const text = generateShareText()
    try {
      await navigator.clipboard.writeText(text)
      setCopied(true)
      setTimeout(() => setCopied(false), 2000)
    } catch (err) {
      console.error('复制失败:', err)
    }
  }

  const handleDownload = () => {
    const text = generateShareText()
    const blob = new Blob([text], { type: 'text/plain' })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = `交易记录_${transaction?.transaction_date}_${transaction?.asset_name}.txt`
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
    URL.revokeObjectURL(url)
  }

  if (!transaction) return null

  return (
    <Dialog open={isOpen} onOpenChange={onClose}>
      <DialogContent className="sm:max-w-md">
        <DialogHeader>
          <DialogTitle>分享交易记录</DialogTitle>
        </DialogHeader>
        <div className="space-y-4">
          <div className="p-4 bg-gray-50 dark:bg-gray-800 rounded-lg">
            <pre className="whitespace-pre-wrap text-sm font-mono">
              {generateShareText()}
            </pre>
          </div>
          <div className="flex gap-2">
            <Button onClick={handleCopy} className="flex-1">
              {copied ? '已复制!' : '复制文本'}
            </Button>
            <Button onClick={handleDownload} variant="outline" className="flex-1">
              下载文本
            </Button>
          </div>
        </div>
      </DialogContent>
    </Dialog>
  )
}

// 添加明细对话框组件
function AddTransactionDialog({
  isOpen,
  onClose,
  assets,
  onAdd,
}: {
  isOpen: boolean
  onClose: () => void
  assets: Asset[]
  onAdd: (payload: { asset_id: number; price: number; notes?: string; transaction_date: string }) => void
}) {
  const today = new Date().toISOString().slice(0, 10)
  const [assetId, setAssetId] = useState<string>(assets[0]?.id?.toString() || '')
  const [price, setPrice] = useState<string>('')
  const [notes, setNotes] = useState<string>('')
  const [date, setDate] = useState<string>(today)

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault()
    const parsedAssetId = parseInt(assetId)
    const parsedPrice = parseFloat(price)
    if (!parsedAssetId || isNaN(parsedPrice)) return
    onAdd({ asset_id: parsedAssetId, price: parsedPrice, notes, transaction_date: date })
    setPrice('')
    setNotes('')
    setDate(today)
  }

  return (
    <Dialog open={isOpen} onOpenChange={onClose}>
      <DialogContent className="sm:max-w-md">
        <DialogHeader>
          <DialogTitle>添加明细</DialogTitle>
        </DialogHeader>
        <form onSubmit={handleSubmit} className="space-y-4">
          <div className="space-y-2">
            <Label htmlFor="tx-date">交易时间</Label>
            <Input id="tx-date" type="date" value={date} onChange={(e) => setDate(e.target.value)} />
          </div>
          <div className="space-y-2">
            <Label>资产名称</Label>
            <Select value={assetId} onValueChange={setAssetId}>
              <SelectTrigger>
                <SelectValue placeholder="选择资产" />
              </SelectTrigger>
              <SelectContent>
                {assets.map((a) => (
                  <SelectItem key={a.id} value={a.id.toString()}>
                    {a.name}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
          <div className="space-y-2">
            <Label htmlFor="tx-price">价格</Label>
            <Input id="tx-price" type="number" step="0.01" value={price} onChange={(e) => setPrice(e.target.value)} required />
          </div>
          <div className="space-y-2">
            <Label htmlFor="tx-notes">备注</Label>
            <Textarea id="tx-notes" value={notes} onChange={(e) => setNotes(e.target.value)} rows={2} />
          </div>
          <div className="flex justify-end space-x-2">
            <Button type="button" variant="outline" onClick={onClose}>取消</Button>
            <Button type="submit" disabled={!assetId || !price}>添加</Button>
          </div>
        </form>
      </DialogContent>
    </Dialog>
  )
}

// 添加分类表单组件
function AddCategoryForm({ onClose }: { onClose: () => void }) {
  const [formData, setFormData] = useState({
    name: '',
    icon: '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 2L2 7l10 5 10-5-10-5zM2 17l10 5 10-5M2 12l10 5 10-5"/></svg>',
    color: '#3B82F6',
    balance: 0,
    limit: 0,
    notes: '',
    status: 'active' as 'active' | 'inactive'
  })

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault()
    onClose()
    setFormData({ 
      name: '', 
      icon: '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 2L2 7l10 5 10-5-10-5zM2 17l10 5 10-5M2 12l10 5 10-5"/></svg>', 
      color: '#3B82F6',
      balance: 0,
      limit: 0,
      notes: '',
      status: 'active'
    })
  }

  return (
    <form onSubmit={handleSubmit} className="space-y-4">
      <div className="space-y-2">
        <Label htmlFor="category-name">分类名称</Label>
        <Input
          id="category-name"
          value={formData.name}
          onChange={(e) => setFormData(prev => ({ ...prev, name: e.target.value }))}
          placeholder="例如：股票、基金、加密货币"
          required
        />
      </div>
      
      <div className="space-y-2">
        <Label htmlFor="category-icon">分类图标 (SVG)</Label>
        <Textarea
          id="category-icon"
          value={formData.icon}
          onChange={(e) => setFormData(prev => ({ ...prev, icon: e.target.value }))}
          placeholder="粘贴SVG代码"
          rows={3}
        />
      </div>
      
      <div className="space-y-2">
        <Label>分类颜色</Label>
        <Input
          type="color"
          value={formData.color}
          onChange={(e) => setFormData(prev => ({ ...prev, color: e.target.value }))}
          className="h-10 w-20 p-1"
        />
      </div>
      
      <div className="space-y-2">
        <Label htmlFor="balance">余额</Label>
        <Input
          id="balance"
          type="number"
          step="0.01"
          value={formData.balance}
          onChange={(e) => setFormData(prev => ({ ...prev, balance: parseFloat(e.target.value) || 0 }))}
          placeholder="0.00"
        />
      </div>

      <div className="space-y-2">
        <Label htmlFor="limit">额度</Label>
        <Input
          id="limit"
          type="number"
          step="0.01"
          value={formData.limit}
          onChange={(e) => setFormData(prev => ({ ...prev, limit: parseFloat(e.target.value) || 0 }))}
          placeholder="0.00"
        />
      </div>
      
      <div className="space-y-2">
        <Label htmlFor="notes">备注</Label>
        <Textarea
          id="notes"
          value={formData.notes}
          onChange={(e) => setFormData(prev => ({ ...prev, notes: e.target.value }))}
          placeholder="可选备注信息"
          rows={2}
        />
      </div>
      
      <div className="space-y-2">
        <Label htmlFor="status">状态</Label>
        <Select value={formData.status} onValueChange={(value: 'active' | 'inactive') => setFormData(prev => ({ ...prev, status: value }))}>
          <SelectTrigger>
            <SelectValue />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="active">启用</SelectItem>
            <SelectItem value="inactive">停用</SelectItem>
          </SelectContent>
        </Select>
      </div>
      
      <div className="flex gap-2">
        <Button type="submit" className="flex-1">
          添加分类
        </Button>
        <Button type="button" variant="outline" onClick={onClose}>
          取消
        </Button>
      </div>
    </form>
  )
}

// 添加收益对话框组件
function AddRevenueDialog({ 
  isOpen, 
  onClose, 
  onAdd 
}: { 
  isOpen: boolean
  onClose: () => void
  onAdd: (amount: number) => void
}) {
  const [amount, setAmount] = useState('')

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault()
    const numAmount = parseFloat(amount)
    if (!isNaN(numAmount)) {
      onAdd(numAmount)
      setAmount('')
      onClose()
    }
  }

  return (
    <Dialog open={isOpen} onOpenChange={onClose}>
      <DialogContent className="sm:max-w-md">
        <DialogHeader>
          <DialogTitle>添加收益</DialogTitle>
        </DialogHeader>
        <form onSubmit={handleSubmit} className="space-y-4">
          <div className="space-y-2">
            <Label htmlFor="revenue-amount">收益金额</Label>
            <Input
              id="revenue-amount"
              type="number"
              step="0.01"
              placeholder="请输入收益金额"
              value={amount}
              onChange={(e) => setAmount(e.target.value)}
              required
            />
          </div>
          <div className="flex justify-end space-x-2">
            <Button type="button" variant="outline" onClick={onClose}>
              取消
            </Button>
            <Button type="submit" disabled={!amount}>
              添加
            </Button>
          </div>
        </form>
      </DialogContent>
    </Dialog>
  )
}

  // 添加支出对话框组件
  function AddExpenseDialog({ 
  isOpen, 
  onClose, 
  onAdd 
}: { 
  isOpen: boolean
  onClose: () => void
  onAdd: (amount: number) => void
}) {
  const [amount, setAmount] = useState('')

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault()
    const numAmount = parseFloat(amount)
    if (!isNaN(numAmount)) {
      onAdd(numAmount)
      setAmount('')
      onClose()
    }
  }

  return (
    <Dialog open={isOpen} onOpenChange={onClose}>
      <DialogContent className="sm:max-w-md">
        <DialogHeader>
          <DialogTitle>添加支出</DialogTitle>
        </DialogHeader>
        <form onSubmit={handleSubmit} className="space-y-4">
          <div className="space-y-2">
            <Label htmlFor="expense-amount">支出金额</Label>
            <Input
              id="expense-amount"
              type="number"
              step="0.01"
              placeholder="请输入支出金额"
              value={amount}
              onChange={(e) => setAmount(e.target.value)}
              required
            />
          </div>
          <div className="flex justify-end space-x-2">
            <Button type="button" variant="outline" onClick={onClose}>
              取消
            </Button>
            <Button type="submit" disabled={!amount}>
              添加
            </Button>
          </div>
        </form>
      </DialogContent>
    </Dialog>
  )
}


